import csv

import pandas as pd
import akshare as ak


def read_csv_and_print(file_path, encoding='utf-8-sig'):
    """
    读取 CSV 文件并循环遍历打印每一行数据

    参数:
        file_path (str): CSV 文件路径
        encoding (str): 文件编码，默认 'utf-8-sig'（兼容带 BOM 的 UTF-8）
    """
    try:
        with open(file_path, 'r', encoding=encoding, newline='') as csvfile:
            # 创建 CSV 读取器（默认以逗号分隔，可通过 delimiter 参数修改分隔符）
            csv_reader = csv.reader(csvfile)
            dict_reader = csv.DictReader(csvfile)
            data_dicts = list(dict_reader)
            for data_dict in data_dicts:
                print(data_dict)

            # 读取表头（如果有）
            headers = next(csv_reader, None)
            if headers:
                print("表头：", headers)
                print("-" * 50)  # 分隔线

            # 循环遍历每一行数据
            row_num = 1  # 行号（从 1 开始，跳过表头）
            for row in csv_reader:
                print(f"第 {row_num} 行：", row)
                row_num += 1

    except FileNotFoundError:
        print(f"错误：未找到文件 {file_path}")
    except UnicodeDecodeError:
        print(f"错误：文件编码不正确，请尝试修改 encoding 参数（当前使用：{encoding}）")
    except Exception as e:
        print(f"读取失败：{str(e)}")


def pandas_csv_to_dicts(file_path, encoding='utf-8-sig'):
    try:
        # 读取 CSV 为 DataFrame
        df = pd.read_csv(file_path, encoding=encoding)
        # 转换为字典列表（orient='records' 表示按行转换）
        data_dicts = df.to_dict(orient='records')
        return data_dicts
    except Exception as e:
        print(f"转换失败：{str(e)}")
        return []


if __name__ == "__main__":
    # 替换为你的 CSV 文件路径
    csv_file_path = "../crud/GPLIST.csv"
    symbol_ = '600081'
    # read_csv_and_print(csv_file_path)
    result = pandas_csv_to_dicts(csv_file_path)
    for row in result:
        if str(row['A股代码']) == symbol_:
            print(row)

    print("-" * 50)
    # stock_individual_info_em_df = ak.stock_individual_info_em(symbol=symbol_)
    # print(stock_individual_info_em_df)
    year_ = f'2015'
    stock_zh_a_hist_df = ak.stock_zh_a_hist(symbol=symbol_, period="daily",
                                            start_date=f"20000101",
                                            end_date=f'20251231',
                                            adjust="hfq")

    # stock_zh_a_hist_tx_df = ak.stock_zh_a_hist_tx(symbol=symbol_, start_date=f"{year_}0101", end_date=f'{year_}1231',
    #                                               adjust="hfq")
    # stock_zh_a_hist_tx_df = ak.stock_zh_a_hist_tx(symbol="sz000001", start_date="20200101", end_date="20201231",
    #                                               adjust="hfq")
    # print(stock_zh_a_hist_tx_df)
    # print(stock_zh_a_hist_tx_df)
    # stock_zh_a_hist_tx_df.to_csv(f"../crud/tx_{symbol_}_{year_}.csv", encoding="utf-8-sig", index=False, header=True)

    # print(stock_zh_a_hist_df)
    stock_zh_a_hist_df.to_csv(f"../crud/shina_{symbol_}_all.csv", encoding="utf-8-sig", index=False, header=True)
